﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SY.BasicData.Api.Write.Basic.Applications.Slaughter.Command;
using SY.BasicData.Domain.SlaughterInformation;
using SY.BasicData.ErrorCode;
using SY.BasicData.Infrastructures;

namespace SY.BasicData.Api.Write.Basic.Applications.Slaughter.CommandHandler
{
    public class UpdateSlaughterCommandHandler : IRequestHandler<UpdateSlaughterCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<SlaughterModel> slaughterRepository;
        private readonly IMapper mapper;

        public UpdateSlaughterCommandHandler(IBaseRepository<SlaughterModel> slaughterRepository, IMapper mapper)
        {
            this.slaughterRepository = slaughterRepository;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(UpdateSlaughterCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "屠宰信息修改成功";

            var slaughter = await slaughterRepository
                .GetAll()
                .Where(x => x.Id == request.Id)
                .FirstOrDefaultAsync(cancellationToken);

            if (slaughter == null)
            {
                result.Message = "找不到编号";
                result.Code = ApiEnum.Fail;
                return result;
            }

            mapper.Map(request, slaughter);

            var affected = await slaughterRepository.Update(slaughter);
            result.Code = affected > 0 ? ApiEnum.Success : ApiEnum.Fail;
            result.Message = affected > 0 ? "屠宰信息修改成功" : "屠宰信息修改失败";
            result.Data = affected;
            return result;
        }
    }
}
